package com.aduerr.v1shouyin.mvp.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import androidx.annotation.NonNull;
import android.text.TextUtils;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aduerr.v1shouyin.App;
import com.aduerr.v1shouyin.R;
import com.aduerr.v1shouyin.common.DatabaseManager;
import com.aduerr.v1shouyin.entity.MemberConsumeDetailEntity;
import com.aduerr.v1shouyin.entity.RefundMEntity;
import com.aduerr.v1shouyin.entity.TransactionFlowEntity;
import com.aduerr.v1shouyin.http.APIRetrofit;
import com.aduerr.v1shouyin.http.RXRequest;
import com.aduerr.v1shouyin.mvp.base.BaseActivity;
import com.aduerr.v1shouyin.mvp.presenter.RefoundMoneyDetailPresenter;
import com.aduerr.v1shouyin.mvp.view.RefoundMoneyDetailView;
import com.aduerr.v1shouyin.print.PrinterWrapper;
import com.aduerr.v1shouyin.util.MoneyTextWatcher;
import com.aduerr.v1shouyin.util.NetUtils;
import com.aduerr.v1shouyin.util.SharedPreferencesUtils;
import com.aduerr.v1shouyin.util.ToastUtils;
import com.aduerr.v1shouyin.view.BandOrUnbandGuidResultDialog;
import com.aduerr.v1shouyin.view.SecurityCodeView;
import com.google.gson.Gson;
import com.orhanobut.hawk.Hawk;

import java.text.DecimalFormat;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;


/**
 * @author HI
 * @email dev1024@foxmail.com
 * @time 2019/5/28 16:35
 * @change
 * @chang time
 * @class describe
 */

public class MemberRefundActivity extends BaseActivity<RefoundMoneyDetailView,
        RefoundMoneyDetailPresenter> implements RefoundMoneyDetailView {


    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.tv_redound_money)
    EditText tvRedoundMoney;
    @BindView(R.id.et_remark)
    EditText etRemark;
    @BindView(R.id.realymoney)
    TextView realymoney;
    @BindView(R.id.ordermoney)
    TextView ordermoney;
    @BindView(R.id.tv_cut_money)
    TextView tvCutMoney;
    @BindView(R.id.tv_pay_type)
    TextView tvPayType;
    String payMoney, orderMoney, cutMoney, payType, orderId;
    Dialog dialog;
    SecurityCodeView securityCodeView;
    private String handinputmoney;
    private BandOrUnbandGuidResultDialog bandOrUnbandGuidResultDialogfail;
    String content[] = new String[20];

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_member_refund);
        ButterKnife.bind(this);
        initData();
        initUI();
    }

    @NonNull
    @Override
    public RefoundMoneyDetailPresenter createPresenter() {
        return new RefoundMoneyDetailPresenter(App.getApp());
    }

    @Override
    protected void onNetworkDisConnected() {

    }

    @Override
    protected void onNetworkConnected(NetUtils.NetType type) {

    }

    @Override
    public void initUI() {
        tvTitle.setText("退款信息");
        tvRedoundMoney.setText(payMoney);
        realymoney.setText(payMoney);
        ordermoney.setText(orderMoney);
        tvCutMoney.setText(cutMoney);
        tvPayType.setText(payType);
        tvRedoundMoney.addTextChangedListener(new MoneyTextWatcher(tvRedoundMoney));
    }

    @Override
    public void initData() {
        payMoney = getIntent().getStringExtra("pay_money");
        orderMoney = getIntent().getStringExtra("order_money");
        cutMoney = getIntent().getStringExtra("cut_money");
        payType = getIntent().getStringExtra("pay_type");
        orderId = getIntent().getStringExtra("order_id");
    }

    @OnClick({R.id.img_back, R.id.tv_confim_refound})
    public void onViewClicked(View view) {
        switch(view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.tv_confim_refound:
                //条件筛选
                handinputmoney = tvRedoundMoney.getText().toString();
                if(TextUtils.isEmpty(handinputmoney)) {
                    ToastUtils.showToast(MemberRefundActivity.this, "退款金额不能为空");
                    return;
                }
                Double aDouble = Double.valueOf(handinputmoney);
                if(aDouble <= 0) {
                    ToastUtils.showToast(MemberRefundActivity.this, "请输入正确的退款金额");
                    return;
                }

                Double bDouble = Double.valueOf(orderMoney);
                if(aDouble > bDouble) {//手动输入的比实际金额还有大
                    ToastUtils.showToast(MemberRefundActivity.this, "退款金额不能大于原订单金额");
                    return;
                }

                toDialogActivity(handinputmoney);
                break;
        }
    }

    private void toDialogActivity(String handinputmoney) {
        View view =
                LayoutInflater.from(MemberRefundActivity.this).inflate(R.layout.dialog_tuikuan, null);
        // 对话框
        dialog = new Dialog(MemberRefundActivity.this);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.show();
        // 设置宽度为屏幕的宽度
        WindowManager windowManager = this.getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = (int) (display.getWidth()); // 设置宽度
        dialog.getWindow().setAttributes(lp);
        dialog.getWindow().setContentView(view);
        //==================================弹出键盘================================================================
        dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        //===========================================================================================================
//        InputTools.KeyBoard(et_hexiao, "open");
//        InputTools.HideKeyboard(et_hexiao);
        //findview
        //找到自定义的控件用来显示密码
        securityCodeView = (SecurityCodeView) view.findViewById(R.id.scv_edittext);
        securityCodeView.setInputCompleteListener(new SecurityCodeView.InputCompleteListener() {
            @Override
            public void inputComplete() {
                dialog.hide();
                getPresenter().toTuikuan(MemberRefundActivity.this,
                        securityCodeView.getEditContent(), orderId, handinputmoney,
                        etRemark.getText().toString());
            }

            @Override
            public void deleteContent(boolean isDelete) {
                //DO NO THING
            }
        });
    }

    @Override
    public void onRefoundMoneyDetailView(RefundMEntity refundMEntity) {
        int success = refundMEntity.getSuccess();
        if(success == 1) {
           /* java.text.SimpleDateFormat sdFormatter = new java.text.SimpleDateFormat
           ("yyyy-MM-dd HH:mm:ss");
            Date curDate = new Date(System.currentTimeMillis());
            String currentime = sdFormatter.format(curDate);
            content[11] = currentime;//退款时间
            content[12] = tvRedoundMoney.getText().toString();//退款金额
            content[15] = etRemark.getText().toString();//退款备注
            OrderRecordEntity order = new OrderRecordEntity();
            order.setMerchantName(content[14]);
            order.setOrderId(content[6]);
            if (date.getPaytype().equals("微信")) {
                order.setType(11);
            } else if (date.getPaytype().equals("支付宝")) {
                order.setType(10);
            }
            order.setOrderMoney(content[0]);
            order.setRefundMoney(content[12]);
            order.setRefundTime(content[11]);
            order.setShopName(content[8]);
            order.setCashier(content[9]);
            order.setCustomer(content[13]);
            order.setPayTime(content[5]);
            order.setRemarks(content[10]);
            order.setRefundRemarks(content[15]);
            DatabaseManager.getInstance().insert(order);*/

            getOrderDetail(orderId);

            ToastUtils.showToast(MemberRefundActivity.this, "退款成功");
            finish();

        } else if(success == -100 | success == -200) {
            //// TODO: 2017/12/9 0009 绑定guid  界面
            SharedPreferencesUtils.remove(MemberRefundActivity.this, "autologin");
            SharedPreferencesUtils.remove(MemberRefundActivity.this, "remberpassword");
            startActivity(new Intent(MemberRefundActivity.this, BangGuidActivity.class));
            finish();
        } else if(success == -300 || success == -2 || success == -3 || success == -6) {
            //// TODO: 2017/12/9 0009 去登录的界面
            com.blankj.utilcode.util.ToastUtils.showShortSafe(refundMEntity.getErrMsg());
            SharedPreferencesUtils.remove(MemberRefundActivity.this, "autologin");
            SharedPreferencesUtils.remove(MemberRefundActivity.this, "remberpassword");
            startActivity(new Intent(MemberRefundActivity.this, LoginActivity.class));
            finish();
        } else {
            //输入密码错误! 回复点击事件!!
            ToastUtils.showToast(context, refundMEntity.getErrMsg() + "");
            bandOrUnbandGuidResultDialogfail =
                    new BandOrUnbandGuidResultDialog(MemberRefundActivity.this,
                            R.style.loading_dialog, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            bandOrUnbandGuidResultDialogfail.dismiss();
                        }
                    }, 105);
            bandOrUnbandGuidResultDialogfail.show();
            bandOrUnbandGuidResultDialogfail.setMoney(handinputmoney);
        }
    }


    @Override
    public void showProgress() {

    }

    @Override
    public void onCompleted() {

    }

    @Override
    public void onError(Throwable e) {

    }


    private void getOrderDetail(String orderId) {

        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("orderid", orderId);
        APIRetrofit.getAPIService().getMemeberConsmeDetail(RXRequest.getXingPosParams(addParams
                , this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(entity -> {
                    if(entity.getSuccess() == 1) {
                        MemberConsumeDetailEntity.DataBean dataBean = entity.getData();
                        if(dataBean.getPayType() == 0) {
                            content[3] = "微信";

                        } else if(dataBean.getPayType() == 1) {
                            content[3] = "支付宝";

                        } else if(dataBean.getPayType() == 2) {
                            content[3] = "储值卡";

                        } else if(dataBean.getPayType() == 3) {
                            content[3] = "云闪付";
                        }


                        //小票优化后统一使用下面的格式
                        content[0] = dataBean.getOrderId();//订单编号
                        content[1] = dataBean.getShopName();//门店
                        content[2] = dataBean.getSiteUserName();//收银员
                        content[4] = "已支付";//支付状态
                        content[5] = dataBean.getPayTime();//支付时间
                        content[6] =
                                new DecimalFormat("0.00").format(dataBean.getOrderMoney());//订单金额
                        double temp =
                                dataBean.getOrderMoney() - dataBean.getLevelDiscount() - dataBean.getSellerHongBaoAmount() - dataBean.getRefundMoney();
                        content[7] = new DecimalFormat("0.00").format(temp);//实收金额
                        content[8] =
                                new DecimalFormat("0.00").format(dataBean.getRefundMoney());
                        ;//退款金额
                        content[9] = dataBean.getRemark();//订单备注
                        content[10] = dataBean.getRefundRemark();//退款备注
                        content[11] = dataBean.getRefundTime();//退款时间
                        content[12] = Hawk.get("company");//账号公司
                        content[17] = dataBean.getRefundUserName();//不一定存在


                        TransactionFlowEntity tfEntity = new TransactionFlowEntity();
                        String json = new Gson().toJson(content);
                        tfEntity.setPrintType(10);
                        tfEntity.setJson(json);


                        DatabaseManager.getInstance().insert(tfEntity);
                        print();

                    } else {
                        ToastUtils.showToast(this, entity.getErrMsg());
                        finish();
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    ToastUtils.showToast(this, "网络异常");
                    finish();
                });

    }


    public void print() {
        int printPage = (int) SharedPreferencesUtils.getParam(MemberRefundActivity.this
                , "printpage", 1);
        if(printPage == 0) {
            ToastUtils.showToast(MemberRefundActivity.this, "打印张数设置为不打印,请先设置打印张数!!");

        } else {

            if(content != null) {

                PrinterWrapper.printNewRefundOrder(printPage, true, content);
            }
        }

    }

}


